﻿using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Lesson14_UDP服务端
{
    class Program
    {
        static void Main(string[] args)
        {
            string host = "127.0.0.1";
            int port = 8080;
            #region 实现UDP服务端通信 收发字符串
            //1.创建套接字
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //2.绑定本机地址
            IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(host), port);
            socket.Bind(ipPoint);
            Console.WriteLine("服务已开启({0}:{1}).", host, port);
            //3.接受消息
            byte[] recvBytes = new byte[512];
            EndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
            int recvLen = socket.ReceiveFrom(recvBytes, ref remotePoint);
            Console.WriteLine("recv  remote:{0}:{1} len:{2} msg:{3}",
                (remotePoint as IPEndPoint).Address.ToString(),
                (remotePoint as IPEndPoint).Port.ToString(),
                recvLen,
                Encoding.UTF8.GetString(recvBytes, 0, recvLen));
            //4.发送到指定目标
            socket.SendTo(Encoding.UTF8.GetBytes("三体世界欢迎您!"), remotePoint);
            //5.释放关闭
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
            #endregion
        }
    }
}